<?php
/**
 * User:chendenan
 * Created On 2022/3/19 0019 21:23
 */
namespace app\common\business;
use app\common\lib\Arr as ArrLib;
use app\common\model\mysql\Goods as GoodsModel;
use app\common\business\{GoodsSku as GoodsSkuBus,SpecsValue as SpecsValueBus};
use think\facade\Cache;
class Goods extends BusBase{
    public $model = null;
    public function __construct(){
        $this->model = new GoodsModel();
    }
    public function getLists($data,$num=10){
        $likeKeys = [];
        if(!empty($data)){
            $likeKeys = array_keys($data);
        }
        try{
            $list = $this->model->getLists($likeKeys,$data,$num);
            $result = $list->toArray();
        }catch (\Exception $e){
            $result = ArrLib::getPaginateDefaultData($num);
        }
        return $result;
    }

    /**
     * 插入商品信息
     * @param $data
     * @return bool|null
     */
    public function insertData($data){
        //开启一个事务
        $this->model->startTrans();
        try {
            $goodsId = $this->add($data);
            if (!$goodsId) {
                return $goodsId;
            }
            /* 执行数据插入到SKU表中 */
            //如果是统一规格
            if ($data['goods_specs_type'] == 1) {

                //统一规格预留插入数据库操作未完成
                //sku信息同样需要插入到sku表
                $goodsSkuBusObj = new GoodsSkuBus();
                $data['goods_id'] = $goodsId;
                $res = $goodsSkuBusObj->save($data);
                if (!empty($res)) {
                    $goodsUpdateData = [
                        "sku_id" => $res->id,
                    ];
                    //执行完毕后 更新主表中的数据
                    $goodsRes = $this->model->updateById($goodsId, $goodsUpdateData);
                    if (!$goodsRes) {
                        throw new \think\Exception("insertData:goods主表更新失败");
                    }
                }else{
                    throw new \think\Exception("sku表新增失败");
                }
                //return true;
            } elseif ($data['goods_specs_type'] == 2) { //如果是多规格
                $goodsSkuBusObj = new GoodsSkuBus();
                $data['goods_id'] = $goodsId;
                $res = $goodsSkuBusObj->saveAll($data);
                //如果不为空
                if (!empty($res)) {
                    //总库存
                    $stock = array_sum(array_column($res, "stock"));
                    $goodsUpdateData = [
                        "price" => $res[0]['price'],
                        "cost_price" => $res[0]['cost_price'],
                        "stock" => $stock,
                        "sku_id" => $res[0]['id'],
                    ];
                    //执行完毕后 更新主表中的数据
                    $goodsRes = $this->model->updateById($goodsId, $goodsUpdateData);
                    if (!$goodsRes) {
                        throw new \think\Exception("insertData:goods主表更新失败");
                    }
                } else {
                    throw new \think\Exception("sku表新增失败");
                }
            }
            // 提交事务
            $this->model->commit();
            return true;
        }catch (\think\Exception $e){
            trace($e->getMessage(),"error");
            // 回滚事务
            $this->model->rollback();
            return false;
        }
        return true;
    }
    public function getRotationChart(){
        $data = [
            "is_index_recommend" => 1,
        ];
        $field = "sku_id as id,title,big_image as image";
        try {
            $result = $this->model->getGoodsByCondition($data,$field,5);
        } catch (\Exception $e){
            return [];
        }
        return $result->toArray();
    }
    public function categoryGoodsRecommend($categoryIds){
        if(!$categoryIds){
            return [];
        }
        $result = [];
        //获取栏目
        //获取栏目数据
        foreach ($categoryIds as $key => $categoryId){
            $result[$key]["categorys"] = (new Category())->getCategoryById($categoryId);
            $result[$key]["goods"] = $this->getGoodsFindInSetCategoryId($categoryId);
        }
        return $result;
    }

    /**
     * 查询栏目下的商品
     * @param $categoryId
     * @return array
     */
    public function getGoodsFindInSetCategoryId($categoryId){
        $field = "sku_id as id,title,price,recommend_image as image";
        try{
            $result = $this->model->getGoodsFindInSetCategoryId($categoryId,$field);
        }catch (\Exception $e){
            trace($e->getMessage(),"error");
            return [];
        }
        return $result->toArray();
    }

    /**
     * 查询商品信息
     * @param $data
     * @param $num
     * @param $order
     * @return array
     */
    public function getNormalLists($data,$num=5,$order){
        try{
            $field = "sku_id as id,title,recommend_image as image,price";
            $list = $this->model->gettNormalLists($data,$num,$field,$order);
            $res = $list->toArray();
            $result = [
                "total_page_num" => isset($res["last_page"])?$res['last_page']:0,
                "count" => isset($res["total"])?$res['total']:0,
                "page" => isset($res["current_page"])?$res['current_page']:0,
                "page_size" => $num,
                "list" => isset($res["data"])?$res['data']:[],
            ];
        }catch (\Exception $e){
            trace($e->getMessage(),"error");
            $result = [];
        }
        return $result;
    }
    public function getGoodsDetailBySkuId($skuId){
        $skuBusObj = new GoodsSkuBus();
        $goodsSku = $skuBusObj->getSkuAndGoods($skuId);
        if(!$goodsSku){
            return [];
        }
        if(empty($goodsSku['goods'])){
            return [];
        }
        $goods = $goodsSku['goods'];
        $skus = $skuBusObj->getSkusByGoodsId($goods['id']);
        if(!$skus){
            return [];
        }
        $flagValue = "";
        foreach ($skus as $sv){
            if($sv['id'] == $skuId){
                $flagValue = $sv['specs_value_ids'];
            }
        }
//        $gids = [];
//        foreach ($skus as $sku){
//            $gids[$sku['specs_value_ids']] = $sku['id'];
//        }
        $gids = array_column($skus,"id","specs_value_ids");
        if($goods['goods_specs_type']==1){
            $sku = [];//单规格
        }else{
            $sku = (new SpecsValueBus())->detailGoodsSkus($gids,$flagValue); //多规格
        }
        $result = [
            "title" => $goods['title'],
            "price" => $goodsSku['price'],
            "cost_price" => $goodsSku['cost_price'],
            "sales_count" => 0,
            "stock" => $goodsSku['stock'],
            "gids" => $gids,
            "image" => $goods['carousel_image'],
            "sku" => $sku,
            "detail" => [
                "d1" => [
                    "商品编码" => $goodsSku['id'],
                    "上架时间" => $goods['create_time'],
                ],
                "d2" => preg_replace('/(<img.+?src=")(.*?)/','$1'.request()->domain().'$2',$goods['description']),
            ],
        ];
        //记录数据到redis 作为商品PV统计
        Cache::inc("mall_pv_".$goods['id']);
        return $result;
    }

    public function updateStock($data){
        try {
            $this->model->decStock($data['id'],$data['stock']);
        } catch (\Exception $e){
            trace($e->getMessage(),"error");
            return false;
        }
    }
    /**
     * 批量更新库存
     * @param $data
     * @return bool
     */
    public function updateAllStock($data){
        if(!is_array($data)){
            return false;
        }
        try {
            $this->model->saveAll($data);
            return true;
        } catch (\Exception $e) {
            trace($e->getMessage(),"error");
            return false;
        }
    }

    public function getInIds($ids){
        try{
            $result = $this->model->getInIds($ids);
        }catch (\Exception $e){
            trace($e->getMessage(),"error");
            return [];
        }
        return $result->toArray();
    }


}